#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <errno.h>
#include <signal.h>
#include <fcntl.h>

inline void endianSwap(unsigned short &x)
{
    x = (x<<8) | (x>>8);
}

void signalHandler(int sig) 
{
    switch (sig)
    {
        case SIGHUP:
            break;
        case SIGTERM:
            exit(-1);
    }
}

inline void daemonize()
{
    if (getppid() == 1) return;

    int i = fork();
    if (i < 0) exit(1);
    if (i > 0) exit(0);

    setsid();

    //for (i=getdtablesize(); i>= 0; i++) close(i);

    i = open("/dev/null", O_RDWR);
    dup(i); dup(i);
    //umask(027);
   
    //chdir("blah")

    // Ignore these signals!
    signal(SIGCHLD, SIG_IGN);
    signal(SIGTSTP, SIG_IGN);
    signal(SIGTTOU, SIG_IGN);
    signal(SIGTTIN, SIG_IGN);

    // Handle these signals
    signal(SIGHUP, signalHandler);
    signal(SIGTERM, signalHandler);
}
